package com.grupit.engine.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

import com.grupit.domain.jdo.User;
import com.grupit.engine.service.NoteService;
import com.grupit.engine.service.impl.mybatis.dao.DaoFactory;
import com.grupit.engine.service.impl.mybatis.dao.generated.NoteVOMapper;
import com.grupit.engine.service.impl.mybatis.model.generated.NoteVO;
import com.grupit.engine.service.impl.mybatis.model.generated.NoteVOExample;
import com.seleniti.pozit.controller.common.domain.Note;

public class MyBatisPoZit4GrupitServiceImpl implements NoteService {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(MyBatisPoZit4GrupitServiceImpl.class);

	@Override
	public Note findPoZitById(Long poZit4GrupitId) throws IOException {
		if (logger.isDebugEnabled()) {
			logger.debug("findPoZitById(Long) - start"); //$NON-NLS-1$
		}

		DaoFactory daoFactory = DaoFactory.openTransaction();

		try {
			NoteVOMapper nm = daoFactory.getNoteMapper();

			NoteVO elm = nm.selectByPrimaryKey(poZit4GrupitId);

			Note result = (elm != null) ? pozit4note(elm) : null;

			if (logger.isDebugEnabled()) {
				logger.debug("findPoZitById(Long) - end"); //$NON-NLS-1$
			}
			return result;
		} finally {
			daoFactory.endTransaction();
		}
	}

	@Override
	public List<Note> findAllNotesByUser(User user) throws IOException {
		if (logger.isDebugEnabled()) {
			logger.debug("findAllNotesByUser(User) - start"); //$NON-NLS-1$
		}

		DaoFactory daoFactory = DaoFactory.openTransaction();

		try {
			NoteVOMapper nm = daoFactory.getNoteMapper();

			NoteVOExample example = new NoteVOExample();

			example.createCriteria().andOwnerUserIdEqualTo(user.getId());

			List<NoteVO> list = nm.selectByExample(example);

			List<Note> result = new ArrayList<Note>();

			if (list != null) {
				for (NoteVO elm : list) {
					Note p = pozit4note(elm);
					result.add(p);
				}
			}

			if (logger.isDebugEnabled()) {
				logger.debug("findAllNotesByUser(User) - end"); //$NON-NLS-1$
			}
			return result;
		} finally {
			daoFactory.endTransaction();
		}
	}

	@Override
	public void save(Note poZit4Grupit) throws IOException {
		if (logger.isDebugEnabled()) {
			logger.debug("save(PoZit4Grupit) - start"); //$NON-NLS-1$
		}

		DaoFactory daoFactory = DaoFactory.openTransaction();

		try {
			NoteVOMapper nm = daoFactory.getNoteMapper();

			if (poZit4Grupit.getId() == null) {

				logger.info("Insertando nueva nota...");
				NoteVO record = note4pozit(poZit4Grupit);

				nm.insert(record);

				Long noteId = record.getNoteId();
				poZit4Grupit.setNoteId(noteId);
				logger.info("... nuevo ID de la nota: " + noteId);
			} else {
				logger.info(String.format("Actualizando nota %d...", poZit4Grupit.getNoteId()));

				NoteVO record = note4pozit(poZit4Grupit);

				nm.updateByPrimaryKey(record);

				/**
				 * No ha cambiado nada que no sea lo que se ha mandado
				 * actualizar así que no se sube la versión
				 */
			}

			daoFactory.commit();

			logger.info(String.format("Guardado OK en servidor la nota %d (version=%d)", poZit4Grupit.getId(),
					poZit4Grupit.getVersion()));

		} finally {
			daoFactory.endTransaction();
		}

		if (logger.isDebugEnabled()) {
			logger.debug("save(PoZit4Grupit) - end"); //$NON-NLS-1$
		}
	}

	@Override
	public void delete(Note note) throws IOException {
		if (logger.isDebugEnabled()) {
			logger.debug("delete(Note) - start"); //$NON-NLS-1$
		}

		DaoFactory daoFactory = DaoFactory.openTransaction();

		try {
			NoteVOMapper nm = daoFactory.getNoteMapper();

			Long noteId = note.getNoteId();
			nm.deleteByPrimaryKey(noteId);

			daoFactory.commit();

			logger.info(String.format("Eliminado OK en servidor la nota %d", note.getId()));

		} finally {
			daoFactory.endTransaction();
		}

		if (logger.isDebugEnabled()) {
			logger.debug("delete(Note) - end"); //$NON-NLS-1$
		}
	}

	protected Note pozit4note(NoteVO elm) {
		if (logger.isDebugEnabled()) {
			logger.debug("pozit4note(Note) - start"); //$NON-NLS-1$
		}

		Note result = new Note();

		result.setNoteId(elm.getNoteId());
		result.setOwnerUserId(elm.getOwnerUserId() != null ? elm.getOwnerUserId().toString() : null);
		result.setTargetSystemId(elm.getTargetSystemId());
		result.setNoteText(elm.getNoteText());
		result.setX(elm.getX());
		result.setY(elm.getY());

		if (logger.isDebugEnabled()) {
			logger.debug("pozit4note(Note) - end"); //$NON-NLS-1$
		}
		return result;
	}

	protected NoteVO note4pozit(Note poZit4Grupit) {
		if (logger.isDebugEnabled()) {
			logger.debug("note4pozit(PoZit4Grupit) - start"); //$NON-NLS-1$
		}

		NoteVO record = new NoteVO();
		record.setNoteId(poZit4Grupit.getNoteId());
		record.setOwnerUserId(poZit4Grupit.getOwnerUserId() != null ? Long.valueOf(poZit4Grupit.getOwnerUserId())
				: null);
		record.setTargetSystemId(poZit4Grupit.getTargetSystemId());
		record.setNoteText(poZit4Grupit.getNoteText());
		record.setX(poZit4Grupit.getX());
		record.setY(poZit4Grupit.getY());
		record.setLastModified(new Date());

		if (logger.isDebugEnabled()) {
			logger.debug("note4pozit(PoZit4Grupit) - end"); //$NON-NLS-1$
		}
		return record;
	}

}
